var app = getApp();
var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var wxUtil = require('../../utils/wxUtil.js');
var common = require('../../utils/common.js');
var MPage = require('../MPage.js');

Page(common.extendPage(MPage, {
    data: {
        dataLoaded: false,
        myHidden: true,
        submiting: false,
        hideDel: false,
        isNotAny: false,
        addrList: [],
        addressId: '',
        name: '',
        tel: '',
        addr: '',
        province: '',
        city: '',
        county: '',
        provinceId: '',
        cityId: '',
        countyId: '',
        value: [0, 0, 0],
        values: [0, 0, 0],
        provinces: [],
        citys: [],
        countys: [],
        province_id: [],
        city_id: [],
        county_id: [],
        province_name: [],
        city_name: [],
        county_name: [],
    },
    onLoad: function(options) {
        // this._orderOptions = options.orderOptions;
        this._initAddr('isOnload');
        this.provinces();
        this.citys(110000);
        this.countys(110000, 110100)
    },
    onShareAppMessage: function() {
        return {
            title: this.data.shop.shareTitle,
            path: "pages/index/index"
        }
    },
    /**
     * 省市区开
     */
    _open: function(e) {
        var formId = e.detail.formId;
        this.setData({
            condition: true
        })
        common.submitForm(formId);
    },
    /**
     * 省市区关闭
     */
    _close: function(e) {
        this.setData({
            condition: false
        })
        if (e) {
            var formId = e.detail.formId;
            common.submitForm(formId);
        }
    },
    /**
     * 初始化地址列表
     */
    _initAddr: function(isOnload) {
        var _self = this;
        ajax.P('/openapi/CAddress/getAll', {}, function(data) {
            var d = data.result;
            if (d.data) {
                _self.setData({
                    addrList: d.data,
                    isNotAny: false
                })
            } else if (d.length == 0) {
                if (isOnload) {
                    _self.showZanTopTips('您还没有添加收货地址哦,赶紧添加吧');
                    _self.setData({
                        addrList: d,
                        myHidden: false,
                        hideDel: true,
                        isNotAny: true
                    })
                } else {
                    _self.setData({
                        addrList: d,
                        isNotAny: true
                    })
                }

            }
            var addrList = _self.data.addrList;
            addrList.some(function(item) {
                if (item.isDefault == 1) {
                    item.selected = true;
                    _self.setData({
                        addrList,
                    })
                }
            })
        })
        _self.setData({
            dataLoaded: true
        })
    },
    /**
     * 地址保存 
     */
    _submit: function(e) {
        var _self = this;
        var formId = e.detail.formId;

        if (_self.validInput(e.detail.value)) {
            _self.setData({
                dataLoaded: false,
                name: e.detail.value.userName,
                tel: e.detail.value.telPhone.trim(),
                addr: e.detail.value.addr,
                submiting: true
            })
            var addressId = this.data.addressId;
            var addrList = this.data.addrList;
            if (this.data.addressId != '') {
                _self.handleAddr(addressId);
            } else {
                if (_self.data.addrList.length == 0) {
                    _self.handleAddr('', 1, function() {
                        _self._goPrevPage();
                    });
                } else {
                    _self.handleAddr();
                }
            }

            /*
            ** 这个是旧数据,优化后,不需要,留在这里的目的是为了溯源
            ***
            // if (_self.data.goodsId != '') {
            //     setTimeout(function() {
            //         var orderOptions = JSON.parse(_self._orderOptions);
            //         var url = '/pages/confirmOrder/confirmOrder?addressId=' + _self.data.addressId;

            //         Object.keys(orderOptions).forEach(function(key) {
            //             url += '&' + key + '=' + orderOptions[key];
            //         });
            //         wx.redirectTo({
            //             url
            //         });
            //     }, 500)
            // }
            **/

            if (_self.data.condition) {
                _self._close();
            }
        }
        _self.setData({
            dataLoaded: true
        })
        common.submitForm(formId);
    },
    /**
     * 绑定表单输入
     */
    _setName: function(e) {
        var _self = this;
        var name = e.detail.value;
        _self.setData({
            name: name
        })
    },
    _setTel: function(e) {
        var _self = this;
        var tel = e.detail.value;
        _self.setData({
            tel: tel
        })
    },
    proCityCounty: function(e) {
        this.setData({
            proCityCounty: e.detail.value
        })
    },
    _setAddr: function(e) {
        var _self = this;
        var addr = e.detail.value;
        _self.setData({
            addr: addr
        })
    },
    /**
     * 添加地址
     */
    _add: function(evt) {
        var _self = this;
        var formId = evt.detail.formId;
        (function(callBack) {
            _self.provinces(function() {
                _self.citys(110000, function() {
                    _self.countys(110000, 110100, function() {
                        callBack && callBack();
                    });
                });
            });
        })(
            function() {
                _self.setData({
                    myHidden: false,
                    addressId: '',
                    name: '',
                    tel: '',
                    addr: '',
                    hideDel: true,
                    value: [0, 0, 0],
                    values: [0, 0, 0],
                    province: '北京市',
                    city: '市辖区',
                    county: '东城区',
                    provinceId: '110000',
                    cityId: '110100',
                    countyId: '110101'
                })
            })
        common.submitForm(formId);
    },
    /**
     * 取消添加地址
     */
    _cancel: function(e) {
        var _self = this;
        var formId = e.detail.formId;
        _self.setData({
            myHidden: true
        })
        if (_self.data.condition) {
            _self._close();
        }
        common.submitForm(formId);
    },
    /**
     * 编辑地址
     */
    _edit: function(e) {
        var index = parseInt(e.currentTarget.dataset.index);
        var addrList = this.data.addrList;
        var formId = e.detail.formId;
        var _self = this;

        (function(callBack) {
            _self.setData({
                myHidden: false,
                hideDel: false,
                addressId: addrList[index].id,
                name: addrList[index].reName,
                tel: addrList[index].rePhone,
                addr: addrList[index].detailAddr,
                value: [0, 0, 0],
                values: [0, 0, 0],
                dataLoaded: false
            })
            _self.provinces(function() {
                _self.citys(110000, function() {
                    _self.countys(110000, 110100, function() {
                        callBack && callBack();
                    });
                });
            });
        })(
            function() {
                _self.setData({
                    province: addrList[index].provinceName,
                    city: addrList[index].cityName,
                    county: addrList[index].districtName,
                    provinceId: addrList[index].provinceId,
                    cityId: addrList[index].cityId,
                    countyId: addrList[index].districtId,
                    dataLoaded: true
                })
            })
        common.submitForm(formId);
    },
    /**
     * 删除地址
     */
    _del: function(e) {
        var _self = this;
        var formId = e.detail.formId;
        _self.setData({
            dataLoaded: false,
        })
        ajax.G(
            '/openapi/CAddress/del', {
                id: _self.data.addressId
            },
            function(data) {
                _self.setData({
                    myHidden: true
                })
                _self._initAddr();
            }
        )
        if (_self.data.condition) {
            _self._close();
        }
        common.submitForm(formId);
    },
    /**
     * 设置默认值
     */
    _selectDefault: function(e) {
        var _self = this;
        var index = parseInt(e.currentTarget.dataset.index);
        var addrList = this.data.addrList;
        var formId = e.detail.formId;
        _self.setData({
            addressId: addrList[index].id,
        })
        ajax.G(
            '/openapi/CAddress/setDefault', {
                id: _self.data.addressId
            },
            function(data) {
                _self._initAddr();
            })
        common.submitForm(formId);
    },
    /**
     * 请求省数据
     */
    provinces: function(callBack) {
        this.setData({
            province_id: []
        })
        var _self = this;
        ajax.G(
            '/openapi/CAddress/getAllProvince', {},
            function(data) {
                var province_id = _self.data.province_id;
                var province_name = _self.data.province_name;
                var d = data.result;

                _self.setData({
                    provinces: d.data
                })
                for (var i = 0; i < _self.data.provinces.length; i++) {
                    province_id.push(_self.data.provinces[i].region_id);
                    province_name.push(_self.data.provinces[i].region_name);
                }
                _self.setData({
                    province_id: province_id,
                    province_name: province_name,
                    province: province_name[0],
                    provinceId: province_id[0]
                });
                callBack && callBack();
            }
        );

    },
    /**
     * 请求市数据
     */
    citys: function(province_id, callBack) {
        this.setData({
            city_id: []
        })
        var _self = this;

        ajax.G(
            '/openapi/CAddress/getAllCity', {
                province_id: province_id
            },
            function(data) {

                var city_id = _self.data.city_id;
                var city_name = _self.data.city_name;
                var city = _self.data.city;
                var d = data.result;

                _self.setData({
                    citys: d.data
                })
                for (var i = 0; i < _self.data.citys.length; i++) {
                    city_id.push(_self.data.citys[i].region_id);
                    city_name.push(_self.data.citys[i].region_name);
                }
                _self.setData({
                    city_id: city_id,
                    city_name: city_name,
                    city: city_name[0],
                    cityId: city_id[0]
                });
                callBack && callBack();
            }
        );
    },

    /**
     * 请求区数据
     */
    countys: function(province_id, city_id, callBack) {
        var _self = this;

        ajax.G(
            '/openapi/CAddress/getAllDistrict', {
                province_id: province_id,
                city_id: city_id,
            },
            function(data) {
                var county_id = _self.data.county_id;
                var county_name = _self.data.county_name;
                var d = data.result;

                _self.setData({
                    countys: d.data
                })
                for (var i = 0; i < _self.data.countys.length; i++) {
                    county_id.push(_self.data.countys[i].region_id);
                    county_name.push(_self.data.countys[i].region_name)
                }
                _self.setData({
                    county_id: county_id,
                    county_name: county_name,
                    county: county_name[0],
                    countyId: county_id[0]
                });
                callBack && callBack();
            }
        );

    },
    /**
     * 切换省市区
     */
    bindChange: function(e) {
        var val = e.detail.value;
        var t = this.data.values;
        if (val[0] != t[0]) {
            var _self = this;
            var province_id = this.data.province_id;
            var province = this.data.province_name[val[0]];
            var provinceId = province_id[val[0]]
            this.setData({
                city_id: [],
                city_name: [],
                city: "",
                county_id: [],
                county_name: [],
                county: ""
            })
            ajax.G('/openapi/CAddress/getAllCity', {
                province_id: provinceId
            }, function(data) {
                // success
                var city_id = _self.data.city_id;
                var city_name = _self.data.city_name;
                var d = data.result;
                _self.setData({
                    citys: d.data
                })
                for (var i = 0; i < _self.data.citys.length; i++) {
                    city_id.push(_self.data.citys[i].region_id);
                    city_name.push(_self.data.citys[i].region_name);
                }
                _self.setData({
                    city_id: city_id,
                    city_name: city_name,
                    city: city_name[0],
                    cityId: city_id[0]
                });
                _self.countys(provinceId, city_id[0])
            })

            this.setData({
                province: this.data.province_name[val[0]],
                city: this.data.city_name[val[1]],
                county: this.data.county_name[val[2]],
                provinceId: this.data.province_id[val[0]],
                cityId: this.data.cityId,
                countyId: this.data.countyId,
                values: val,
                value: [val[0], 0, 0]
            })
            return;
        }
        if (val[1] != t[1]) {
            var _self = this;
            var province_id = this.data.province_id[val[0]];
            var province = this.data.province_name[val[0]];
            var city_id = _self.data.city_id[val[1]];
            var city = _self.data.city_name[val[1]];
            this.setData({
                county_id: [],
                county_name: [],
                county: ""
            })
            ajax.G('/openapi/CAddress/getAllDistrict', {
                province_id: province_id,
                city_id: city_id
            }, function(data) {
                // success
                var county_id = _self.data.county_id;
                var county_name = _self.data.county_name;
                var d = data.result;
                _self.setData({
                    countys: d.data
                })
                for (var i = 0; i < _self.data.countys.length; i++) {
                    county_id.push(_self.data.countys[i].region_id);
                    county_name.push(_self.data.countys[i].region_name);
                }
                _self.setData({
                    county_id: county_id,
                    county_name: county_name,
                    county: county_name[0],
                    countyId: county_id[0]
                });
            })
            this.setData({
                city: this.data.city_name[val[1]],
                cityId: this.data.city_id[val[1]],
                county: this.data.county_name[val[2]],
                countyId: this.data.county_id[val[2]],
                values: val,
                value: [val[0], val[1], 0]
            })
            return;
        }
        if (val[2] != t[2]) {
            this.setData({
                county: this.data.county_name[val[2]],
                countyId: this.data.county_id[val[2]],
                values: val,
                value: [val[0], val[1], val[2]]
            })
            return;
        }
    },
    handleAddr: function(addressId, isDefault, cb) {
        var _self = this;
        ajax.P(
            '/openapi/CAddress/edit', {
                name: this.data.name,
                phone: this.data.tel,
                detailAddr: this.data.addr,
                provinceId: this.data.provinceId,
                cityId: this.data.cityId,
                districtId: this.data.countyId,
                id: addressId,
                isDefault: isDefault
            },
            function(data) {
                _self.setData({
                    addressId: data.result.id,
                    myHidden: true,
                    submiting: false
                })
                _self._initAddr();
                util.alert('保存成功', function() {
                    cb && cb();
                });
            },
            function(data) {
                _self.setData({
                    submiting: false
                })
            }
        )
    },
    /**
     * 验证输入消息
     */
    validInput: function(inputValue) {
        var {
            userName,
            telPhone,
            addr
        } = inputValue || {};

        if (userName.length == 0) {
            util.alert('请输入您的收货人姓名');
            return false;
        } else if (userName.length > 20) {
            util.alert('收货人长度不能超过20位');
            return false;
        } else if (telPhone.length == 0) {
            util.alert('请输入您的手机号');
            return false;
        } else if (!/^1\d{10}$/.test(telPhone.trim())) {
            util.alert('您输入的手机号格式不正确');
            return false;
        } else if (addr.length == 0) {
            util.alert('请输入您的详细地址');
            return false;

        } else if (addr.length > 100) {
            util.alert('您输入的地址长度不能超过100位');
            return false;
        }
        return true;
    },

    showZanTopTips(content = '', options = {}) {
        var zanTopTips = this.data.zanTopTips || {};
        // 如果已经有一个计时器在了，就清理掉先
        if (zanTopTips.timer) {
            clearTimeout(zanTopTips.timer);
            zanTopTips.timer = undefined;
        }

        if (typeof options === 'number') {
            options = {
                duration: options
            };
        }

        // options参数默认参数扩展
        options = Object.assign({
            duration: 1000
        }, options);

        // 设置定时器，定时关闭topTips
        var timer = setTimeout(() => {
            this.setData({
                'zanTopTips.show': false,
                'zanTopTips.timer': undefined
            });
        }, options.duration);

        // 展示出topTips
        this.setData({
            zanTopTips: {
                show: true,
                content,
                options,
                timer
            }
        });
    },
    /**
     * 页面跳转
     */
    _jump: function(evt) {
        common.jump(evt);
    },
    /**
     * 设置上一个页面的数据,并跳转到上一个页面
     */
    _goPrevPage: function() {
        var _self = this;
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];
        console.log(prevPage);
        prevPage.setData({
            optionAddrId: _self.data.addressId,
            myIf: false
        })
        if (prevPage.route != 'pages/mine/mine') {
            wx.navigateBack({
                delta: 1
            });
        }

    }
}))